import random
import re
from datetime import datetime

from flask import current_app,make_response, jsonify
from flask import request
from flask import session

from info import constants, db
from info import redis_store
from info.models import User
from info.utils.captcha.captcha import captcha
from info.utils.response_code import RET
from . import passport_blue


@passport_blue.route('/logout', methods=['POST'])
def logout():
    session.pop('user_id',None)
    return jsonify(errno=RET.OK,errmsg='退出成功')


@passport_blue.route('/login', methods=['POST'])
def login():
    # 获取数据
    dict_data = request.json
    mobile = dict_data.get('mobile')
    password = dict_data.get('password')
    # 校验参数，为空校验
    if not all([mobile, password]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不全')

    # 通过用户手机号，倒数据库查询用户对象
    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='从数据库取出用户对像失败')

    # 判断用户是否存在
    if not user:
        return jsonify(errno=RET.NODATA, errmsg='用户不存在')

    # 校验密码是否正确
    if not user.check_password(password):
        return jsonify(errno=RET.DATAERR, errmsg='密码错误')

    # 将用户的登录信息保存在session中
    session["user_id"] = user.id

    # 记录用户的最后一次的登录时间
    user.last_login = datetime.now()
    # db.session.commit()

    return jsonify(errno=RET.OK, errmsg='登录成功')


@passport_blue.route('/register', methods=['POST'])
def register():
    # 获取请求中的数据
    # json_data = request.data
    # dict_data = json.loads(json_data)
    dict_data = request.json
    mobile = dict_data.get('mobile')
    sms_code = dict_data.get('sms_code')
    password = dict_data.get('password')
    # 判断请求中的数据是否有空
    if not all([mobile,sms_code,password]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不全')
    # 根据手机号取出redis中的手机验证码，确定手机验证码是否正确
    try:
        redis_sms_code = redis_store.get("sms_code:%s" % mobile)
    except Exception as e:
        current_app.loger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='取出短信验证码失败')

    # 判断短信验证码是否过期
    if not redis_sms_code:
        return jsonify(errno=RET.NODATA,errmsg='短信验证码已过期')

    # 判断短信验证码是否正确
    if sms_code != redis_sms_code:
        return jsonify(errno=RET.DATAERR,errmsg='短信验证码填写错误')

    # 删除短信验证码
    try:
        redis_store.delete("sms_code:%s" % mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='删除短信验证码失败')

    # 已完成所有校验工作，创建用户对象
    user = User()

    # 设置用户对象属性
    user.nick_name = mobile
    # user.password_hash = password
    # 密码的加密处理，setter方法装饰
    user.password = password
    user.mobile = mobile
    user.signature = "该用户很懒，什么都没有写"

    # 保存用户到数据库
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='注册失败')

    # 返回响应
    return jsonify(errno=RET.OK,errmsg='注册成功')


@passport_blue.route('/sms_code', methods=['post'])
def sms_code():
    # 1.获取参数
    # json_data = request.data
    # dict_data = json.loads(json_data)
    dict_data = request.json
    mobile = dict_data.get("mobile")
    image_code = dict_data.get("image_code")
    image_code_id = dict_data.get("image_code_id")

    # 2.校验参数，图片验证码
    # 从redis中取出图片验证码
    # redis_image_code = redis_store.get("image_code:%s"%image_code_id)
    # if redis_image_code != image_code:
    #     return jsonify(errno=10000,errmsg="手机号的格式不匹配")
    # 2.参数的为空校验
    if not all([mobile,image_code,image_code_id]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")

    # 3.校验手机的格式
    if not re.match("1[3-9]\d{9}",mobile):
        return jsonify(errno=RET.DATAERR,errmsg="手机号的格式错误")

    # 4.通过图片验证码获取图片验证码
    try:
        redis_image_code = redis_store.get("image_code:%s" % image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="操作redis失败")

    # 5.判断图片验证码是否过期
    if not redis_image_code:
        return jsonify(errno=RET.NODATA,errmsg="图片验证码已过期")

    # 6.判断图片验证码是否正确
    if image_code.upper() != redis_image_code.upper():
        return jsonify(errno=RET.DATAERR,errmsg="图片验证码填写错误")

    # 7.删除redis中的图片验证码
    try:
        redis_store.delete("image_code:%s" % image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="删除redis图片验证码失败")

    # 8生成一个随机的短信验证码，调用ccp发送短信，判断是否发送成功
    sms_code = "%06d"%random.randint(0,999999)
    # ccp = CCP()
    # result = ccp.send_template_sms(mobile,[sms_code,constants.SMS_CODE_REDIS_EXPIRES/60],1)
    #
    # if result == 0:
    #     return jsonify(errno=RET.DATAERR,errmsg="短信发送失败")
    current_app.logger.debug('短信验证码是%s' % sms_code)

    # 发送短信，调用封装好的ccp
    # ccp = CCP()
    # result = ccp.send_template_sms("18304083796", ['888888', 5], 1)
    # 9.将短信保存到redis中
    try:
        redis_store.set("sms_code:%s" % mobile, sms_code, constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="图片验证码保存到redis失败")

    # 返回响应
    return jsonify(errno=RET.OK,errmsg="短信发送成功")


@passport_blue.route('/image_code')
def image_code():
    # 1获取前端传递的查询参数
    cur_id = request.args.get("cur_id")
    pre_id = request.args.get("pre_id")
    # 2调用genegerate_captcha获取图片验证码编号，验证码值，图片
    name,text,image_data = captcha.generate_captcha()

    # 3将图片验证码保存到redis
    try:
        redis_store.set("image_code:%s"%cur_id,text,constants.IMAGE_CODE_REDIS_EXPIRES)
        # 4判断是否有上一次的图片验证码
        if pre_id:
            redis_store.delete("image_code:%s"%pre_id)
    except Exception as e:
        current_app.logger.error(e)
        return "图片验证码操作失败"
    response = make_response(image_data)
    response.headers["Content-Type"] = "image/png"
    return response